package com.example.repair

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.RepairEntityItem
import com.example.base.mvi.BaseActivity
import com.example.base.mvi.HttpType
import com.example.base.mvi.UiState
import com.example.base.utils.DateTimeUtils
import com.example.repair.databinding.ActivityRepairEditBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlin.math.log

@Route(path = "/repair/RepairEditActivity")
@AndroidEntryPoint
class RepairEditActivity : BaseActivity<ActivityRepairEditBinding,RepairIntent,RepairViewModel>() {

    val repairImgAdapter by lazy { RepairImgAdapter() }
    val imgs = mutableListOf<String>()//接受上传后的图片地址
    override fun getLayout(): Int  = R.layout.activity_repair_edit

    override fun getVM(): Class<RepairViewModel>  = RepairViewModel::class.java

    override fun initView() {
        //初始化
        binding.repairEditRv.apply {
            adapter = repairImgAdapter
            layoutManager = GridLayoutManager(this@RepairEditActivity,4)
        }
        //报修人一般为当前登录人
        binding.repairEditName.setText(SPUtils.getInstance().getString("username"))
        //点击图片进行上传
        binding.repairEditTvimg.setOnClickListener {
            //判断最多上传4张
            if(imgs.size==4){
                ToastUtils.showLong("最多只能上传4张图片")
            }else{
                PictureSelector.create(this,PictureSelector.SELECT_REQUEST_CODE).selectPicture()
            }
        }
        //点击提交，新增维修工单
        binding.submit.setOnClickListener {
            val item = RepairEntityItem(
                binding.repairEditPhone.text.toString(),
                binding.repairEditDesc.text.toString(),
                imgs.joinToString(","),
                0,
                "WX"+DateTimeUtils.getTime(),
                "待处理",
                binding.repairEditLoc.text.toString(),
                binding.repairEditName.text.toString(),
                DateTimeUtils.getDateTime(),
                SPUtils.getInstance().getInt("uid")
            )
            viewModel.sendIntent(RepairIntent.repairAdd(item))
        }

        //图片删除
        repairImgAdapter.addChildClickViewIds(R.id.img_delete)
        repairImgAdapter.setOnItemChildClickListener { adapter, view, position ->
            imgs.removeAt(position)
            repairImgAdapter.data.removeAt(position)
            repairImgAdapter.notifyItemRemoved(position)
        }
    }

    override fun initData() {
        lifecycleScope.launch {
            viewModel.uiState.collect{
                when(it){

                    is UiState.onSuccess<*> -> {
                        when(it.type){
                            HttpType.DEFAULT -> {
                                ToastUtils.showLong("上传成功")
                                //rv显示图片
                                val str = it.data as String
                                val name = str.split(":")[1]
                                imgs.add("http://10.161.9.80:2209/images/repair/${SPUtils.getInstance().getInt("uid").toString()}/"+name)
                                repairImgAdapter.data.clear()
                                repairImgAdapter.data.addAll(imgs)
                                repairImgAdapter.notifyDataSetChanged()
                            }
                            HttpType.ADD->{
                                ToastUtils.showLong("报修成功")
                                finish()
                            }
                            else->{

                            }
                        }
                    }
                    else ->{

                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==PictureSelector.SELECT_REQUEST_CODE&&resultCode== RESULT_OK){
            val bean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            val path = bean.path
            Log.d("sss", "onActivityResult: $path")
            val fileName = path.split("/").last()
            viewModel.sendIntent(RepairIntent.upload(path,fileName))

        }
    }

}